package io.github.loan.common.util;

import java.util.Date;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * 发送邮件
 * 
 * @author Andone
 *
 */
@Component("springEmailUtil")
public class SpringEmailUtil {
	@Resource
	private JavaMailSender javaMailSender;
	@Resource
	private SimpleMailMessage simpleMailMessage;

	/**
	 * 发送邮件
	 * 
	 * @return
	 */
	public boolean sendMail(String to, String subject, String text) {
		try {
			simpleMailMessage.setTo(to);
			simpleMailMessage.setSubject(subject);
			simpleMailMessage.setText(text);

			javaMailSender.send(simpleMailMessage);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 发送邮件
	 * 
	 * @return
	 */
	public boolean sendHTMLMail(String to, String subject, String text) {
		try {
			MimeMessage mimeMessage = javaMailSender.createMimeMessage();
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

			messageHelper.setTo(to);
			messageHelper.setFrom(this.simpleMailMessage.getFrom());
			messageHelper.setSubject(subject);
			/* 第二个参数:必须为true;表示html */
			messageHelper.setText(text, true);

			javaMailSender.send(mimeMessage);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring/applicationContext_*.xml");
		SpringEmailUtil springEmailUtil = (SpringEmailUtil) ctx.getBean("springEmailUtil");
		String to = "18363992540@163.com";
		String subject = "测试邮件";
		String text = "测<a href='http://baidu.com'>试</a>一" + new Date().toLocaleString() + "下";
		// springEmailUtil.sendMail(to, subject, text);
		springEmailUtil.sendHTMLMail(to, subject, text);
		System.out.println("----------------");
	}
}
